<script setup lang="ts" name="UserEdit">
import { addUserApi, getUserApi, updateUserApi } from "@/api/system/user";
import { DEFAULT_PASSWORD } from "@/views/system/user/const";
import { listDeptApi } from "@/api/system/dept";

const { proxy } = getCurrentInstance();

const { sys_user_sex, sys_normal_disable } = useDict("sys_user_sex", "sys_normal_disable")

const emit = defineEmits(['closeDialog']);

const props = defineProps({
  id: {
    default: '',
  },
  title: {
    type: String,
    default: false,
  }
})

// 用户表单
const userFormRef = ref(null);

// 部门选项
const deptList = ref<DeptRecord[]>([]);

// 岗位选项
const postList = ref<PostRecord[]>([]);

// 角色选项
const roleList = ref<RoleRecord[]>([]);

// 弹窗开关
const open = ref(false);

// 表单数据
const form = ref<UserRecord>({});

// 表单校验
const rules = ref({
  userName: [
    { required: true, message: "用户名称不能为空", trigger: "blur" },
  ],
  password: [
    { required: true, message: "用户密码不能为空", trigger: "blur" },
    { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }
  ],
  nickName: [
    { required: true, message: "用户昵称不能为空", trigger: "blur" },
  ],
  email: [
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
  ],
  phonenumber: [
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  status: [
    { required: true, message: "状态不能为空", trigger: "change" },
  ],
  createTime: [
    { required: true, message: "创建时间不能为空", trigger: "change" },
  ],
  admin: [
    { required: true, message: "是否超管不能为空", trigger: "change" },
  ],
  deptId: [
    { required: true, message: "归属部门不能为空", trigger: "change" },
  ],
  loginDate: [
    { required: true, message: "登陆时间不能为空", trigger: "change" },
  ],
  postIds: [
    { required: true, message: "岗位IP不能为空", trigger: "change" },
  ],
  roleId: [
    { required: true, message: "角色ID不能为空", trigger: "change" },
  ],
});

// 加载
const loading = ref(false);

/** 获取用户详情 */
function getData() {
  reset();

  getUserApi(props.id).then(response => {
    if (!isEmpty(props.id)) {
      form.value = response.data;
      form.value.postIds = response.postIds;
      form.value.roleIds = response.roleIds;
    }
    postList.value = response.posts;
    roleList.value = response.roles;
    open.value = true;
  }).catch(err => {
    console.error(err);
    closeDialog(false);
  })

}

/** 查询部门下拉树结构 */
function getDeptTree() {
  listDeptApi().then(response => {
    deptList.value = handleTree(response.data, "deptId");
  })
}

/** 表单重置 */
function reset() {
  form.value = {
    userId: null,
    userName: null,
    password: DEFAULT_PASSWORD,
    nickName: null,
    email: null,
    sex: null,
    phonenumber: null,
    status: SYS_NORMAL_DISABLE_ENUM.normal,
    createTime: null,
    admin: null,
    avatar: null,
    dept: null,
    deptId: null,
    loginDate: null,
    postIds: [],
    roleId: null,
    roleIds: [],
    roles: null,
    remark: null,
  };
}

/** 关闭弹窗 */
function closeDialog(refresh: boolean) {
  open.value = false;
  emit("closeDialog", refresh);
}

/** 提交按钮 */
function submitForm() {
  // @ts-ignore
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (form.value.userId) {
        updateUserApi(form.value).then(() => {
          // @ts-ignore
          proxy.$modal.msgSuccess("修改成功");
          loading.value = false;
          closeDialog(true);
        }).catch(() => {
          loading.value = false
        });
      } else {
        addUserApi(form.value).then(() => {
          // @ts-ignore
          proxy.$modal.msgSuccess("新增成功");
          loading.value = false;
          closeDialog(true);
        }).catch(() => {
          loading.value = false
        });
      }
    }
  })
}

watch(open, (val) => {
  if (!val) {
    closeDialog(false);
  }
})

getData();
getDeptTree();
</script>
<template>
  <!-- 用户编辑对话框 -->
  <el-dialog :title="title" v-model="open" width="700px" append-to-body :close-on-click-modal="false">
    <el-form ref="userFormRef" :model="form" :rules="rules" :inline="true" label-width="80px">
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
      </el-form-item>
      <el-form-item label="归属部门" prop="deptId">
        <el-tree-select
            v-model="form.deptId"
            :data="deptList"
            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
            check-strictly
            value-key="deptId"
            placeholder="请选择归属部门"
        />
      </el-form-item>
      <el-form-item v-if="!form.userId" label="用户名称" prop="userName">
        <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status" placeholder="请选择状态">
          <el-radio
              :value="item.value"
              v-for="(item, index) in sys_normal_disable"
              :key="index"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="用户性别" prop="sex">
        <el-radio-group v-model="form.sex" placeholder="请选择性别">
          <el-radio
              :value="item.value"
              v-for="(item, index) in sys_user_sex"
              :key="index"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="岗位" prop="postIds">
        <el-select v-model="form.postIds" multiple collapse-tags placeholder="请选择岗位">
          <el-option
              v-for="(item, index) in postList"
              :key="index"
              :label="item.postName"
              :value="item.postId" />
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="roleIds">
        <el-select v-model="form.roleIds" multiple collapse-tags placeholder="请选择角色">
          <el-option
              v-for="(item, index) in roleList"
              :key="index"
              :label="item.roleName"
              :value="item.roleId" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark" class="item-describe">
        <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" v-debounce="submitForm" :loading="loading">确 定</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>

</style>